package com.huitone.gddw.utils;


import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.bin.common.utils.StringUtils;

public class HttpClientUtils {
	private final static Logger LOGGER = Logger.getLogger(HttpClientUtils.class);
	
	
//	/创建https SSL请求客户端
	 public static CloseableHttpClient createSSLClientDefault() {
	        try {
	            //使用 loadTrustMaterial() 方法实现一个信任策略，信任所有证书
	            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
	                // 信任所有
	                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	                    return true;
	                }

	            }).build();
	            //NoopHostnameVerifier类:  作为主机名验证工具，实质上关闭了主机名验证，它接受任何
	            //有效的SSL会话并匹配到目标主机。
	            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
	            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
	            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
	        } catch (KeyManagementException e) {
	            e.printStackTrace();
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        } catch (KeyStoreException e) {
	            e.printStackTrace();
	        }
//	        return HttpClients.createDefault();
	        return null;
	  }
	
	//Post请求
	public static String doPostByJson(String url,String json,String token) {
		 	CloseableHttpClient httpClient = null;
	        CloseableHttpResponse httpResponse = null;
	        String result = "";
	        // 创建httpClient实例
//	        httpClient = HttpClients.createDefault();
	        
	        //https请求
	        httpClient =  createSSLClientDefault();
	        LOGGER.info("测试  75行  httpClient对象== "+httpClient);
			System.out.println("测试  75行  httpClient对象==  "+httpClient);
	        
	        
	        // 创建httpPost远程连接实例
	        HttpPost httpPost = new HttpPost(url);
	        // 配置请求参数实例
	        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
	                .setConnectionRequestTimeout(4000)// 设置连接请求超时时间
	                .setSocketTimeout(6000)// 设置读取数据连接超时时间
	                .build();
	        // 为httpPost实例设置配置
	        httpPost.setConfig(requestConfig);
	        // 设置请求头
	        httpPost.addHeader("Content-Type", "application/json");
	        
	      //如果需要token 应该是这样带上token信息吗?   
	        if(!StringUtils.isEmpty(token)) {
		        httpPost.addHeader("TOKEN", token);
	        }
	        
	        
	        if(!StringUtils.isEmpty(json)) {
	        	try {
					StringEntity s;
					s = new StringEntity(json.toString());
					s.setContentEncoding("UTF-8");
		            s.setContentType("application/json");//发送json数据需要设置contentType
			        httpPost.setEntity(s);
				} catch (UnsupportedEncodingException e) {
					 LOGGER.error("UnsupportedEncodingException异常：  " + e.getMessage(), e);
				}
	        }
			
	        
	        try {
	            // httpClient对象执行post请求,并返回响应参数对象
	            httpResponse = httpClient.execute(httpPost);
	            if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK) {
//		            	 // 从响应对象中获取响应内容
		            HttpEntity entity = httpResponse.getEntity();
		            result = EntityUtils.toString(entity,"utf-8");
	            }else {
	            	 LOGGER.error("接口调用失败,返回http状态码：  " + httpResponse.getStatusLine().getStatusCode());
	            }
	        } catch (ClientProtocolException e) {
	            LOGGER.error("ClientProtocolException异常：" + e.getMessage(), e);
	        } catch (IOException e) {
	            LOGGER.error("IOException异常：" + e.getMessage(), e);
	        } finally {
	            // 关闭资源
	            if (null != httpResponse) {
	                try {
	                    httpResponse.close();
	                } catch (IOException e) {
	                    LOGGER.error("关闭资源 ,httpResponse关闭时IOException异常：" + e.getMessage(), e);
	                }
	            }
	            if (null != httpClient) {
	                try {
	                    httpClient.close();
	                } catch (IOException e) {
	                    LOGGER.error("关闭资源 ,httpClient关闭时IOException异常：" + e.getMessage(), e);
	                }
	            }
	        }
	        return result;
	    }
	
	

	
}
